package com.local.admin.controller;

import com.local.admin.constants.AdminConstants;
import com.local.common.util.ResultUtil;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 通用方法，如验证码、上传图片
 */

@Controller
@RequestMapping("/admin/common")
public class CommonController {


    @Value("${upload.image.save-path}")
    private String imageSavePath;

    @Value("${upload.image.max-size}")
    private Integer imageMaxSize;

    @Value("${upload.image.url}")
    private String imageUrl;

    public static StandardServletMultipartResolver standardServletMultipartResolver = new StandardServletMultipartResolver();


    /**
     * 上传1张图片
     * @param file
     * @param type
     * @return
     */
    @PostMapping("/uploadImage/{type}")
    @ResponseBody
    public ResultUtil uploadImage(@RequestParam("file") MultipartFile file, @PathVariable("type") String type) {
        if (file.getSize() > this.imageMaxSize) {
            return new ResultUtil(400, "图片大小不能超过2M");
        }

        String originalFilename = file.getOriginalFilename();
        //获取图片后缀名，如：.png
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        //新图片名
        String newFileName = sdf.format(new Date()) + new Random().nextInt(100) + suffixName;

        //图片上传目录：总目录 + 图片所属产品类型 + 年月
        String fileBasePath = this.imageSavePath;
        String dateString = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
        String fileTypePath = type + File.separator + dateString + File.separator;
        String fileUploadPath = fileBasePath + fileTypePath;

        File uploadFile = new File(fileUploadPath + newFileName);

        //获取新文件所在目录。并且判断目录是否存在，不存在则创建该目录
        File parentFile = uploadFile.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }

        /**
         * 图片上传
         */
        try {
            file.transferTo(uploadFile);
        } catch (Exception e) {
            return new ResultUtil(400, "图片上传失败，请稍后重试");
//            throw new RuntimeException(e);
        }

        /**
         * 返回图片访问url
         */
        String imageFullUrl = this.imageUrl + type + "/" + dateString + "/" + newFileName;

        return new ResultUtil(200, "", imageFullUrl);
    }


    /**
     * 上传多张图片
     * @param type
     * @return
     */
    @PostMapping("/uploadImages/{type}")
    @ResponseBody
    public ResultUtil uploadImages(@PathVariable("type") String type, HttpServletRequest httpServletRequest) {
        List<MultipartFile> multipartFiles = new ArrayList<>(8);

        if (standardServletMultipartResolver.isMultipart(httpServletRequest)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) httpServletRequest;
            Iterator<String> iter = multiRequest.getFileNames();
            int total = 0;
            while (iter.hasNext()) {
                if (total > 5) {
                    return new ResultUtil(201, "最多上传5张图片");
                }
                total += 1;
                MultipartFile file = multiRequest.getFile(iter.next());
                multipartFiles.add(file);
            }
        }
        if (CollectionUtils.isEmpty(multipartFiles)) {
            return new ResultUtil(201, "参数异常");
        }
        if (multipartFiles.size() > 5) {
            return new ResultUtil(201, "最多上传5张图片");
        }
        List<String> fileNames = new ArrayList(multipartFiles.size());
        for (int i = 0; i < multipartFiles.size(); i++) {
            MultipartFile file = multipartFiles.get(i);
            String originalFilename = file.getOriginalFilename();
            //获取图片后缀名，如：.png
            String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            //新图片名
            String newFileName = sdf.format(new Date()) + new Random().nextInt(100) + suffixName;

            //图片上传目录：总目录 + 图片所属产品类型 + 年月
            String fileBasePath = this.imageSavePath;
            String dateString = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
            String fileTypePath = type + File.separator + dateString + File.separator;
            String fileUploadPath = fileBasePath + fileTypePath;

            File uploadFile = new File(fileUploadPath + newFileName);

            //获取新文件所在目录。并且判断目录是否存在，不存在则创建该目录
            File parentFile = uploadFile.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }

            /**
             * 图片上传
             */
            try {
                file.transferTo(uploadFile);
            } catch (Exception e) {
                return new ResultUtil(201, "图片上传失败，请稍后重试");
//            throw new RuntimeException(e);
            }

            /**
             * 返回图片访问url
             */
            String imageFullUrl = this.imageUrl + type + "/" + dateString + "/" + newFileName;
            fileNames.add(imageFullUrl);

        }

        return new ResultUtil(200, "", fileNames);
    }


    /**
     * 登录验证码
     * @param type
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws Exception
     */
    @GetMapping("/captcha/{type}")
    public void captcha(@PathVariable("type") String type, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/png");

        // 三个参数分别为宽、高、位数
        SpecCaptcha captcha = new SpecCaptcha(150, 40, 4);

        // 设置类型 数字和字母混合
        captcha.setCharType(Captcha.TYPE_DEFAULT);

        //设置字体
        captcha.setCharType(Captcha.FONT_9);

        // 验证码存入session
        httpServletRequest.getSession().setAttribute(AdminConstants.ADMIN_LOGIN_CAPTCHA, captcha.text().toLowerCase());

        // 输出图片流
        captcha.out(httpServletResponse.getOutputStream());
    }
}
